<template>
  <div class="b-u-page">
    <div class="b-u-content">
      <div class="b-u-left">
        <div class="b-u-l-title">
          基础信息
        </div>
        <el-form :model="blogFrom" :rules="blogRules" ref="updateBlogFrom" label-width="60px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="blogFrom.title" clearable placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="前言" prop="preface">
            <el-input v-model="blogFrom.preface" type="textarea" placeholder="博客前言"></el-input>
          </el-form-item>
          <el-form-item label="标签" prop="spaceId">
            <el-select v-model="blogFrom.tagIds" clearable multiple placeholder="请选择博客关联标签列表" class="tag-select">
              <el-option
                v-for="tag in tagList"
                :disabled="tagSelect"
                :key="tag.tagId"
                :label="tag.name"
                :value="tag.tagId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="空间" prop="spaceId">
            <el-select v-model="blogFrom.spaceId" clearable placeholder="请选择博客所属空间" class="space-select">
              <el-option
                v-for="space in spaceList"
                :key="space.spaceId"
                :label="space.name"
                :value="space.spaceId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标记" prop="label">
            <el-select v-model="blogFrom.label" placeholder="请选择博客标记" class="label-select">
              <el-option label="原创" :value="0"></el-option>
              <el-option label="转载" :value="1"></el-option>
              <el-option label="翻译" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <div class="b-u-c-from">
            <div class="b-s-c-f-statement">
              <el-form-item label="版权" prop="showStatement">
                <el-radio-group size="mini" v-model="blogFrom.showStatement">
                  <el-radio :label="0" >开启</el-radio>
                  <el-radio :label="1">关闭</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div class="b-s-c-f-comment">
              <el-form-item label="评论" prop="openComment">
                <el-radio-group size="mini" v-model="blogFrom.openComment">
                  <el-radio :label="0" >开启</el-radio>
                  <el-radio :label="1" >关闭</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </div>
          <el-form-item label="首图" prop="firstPicture">
            <div class="b-u-c-from">
              <el-upload
                class="picture-uploader picture-upload"
                :action="aliUrl"
                :show-file-list="false"
                :data="dataObj"
                :before-upload="uploadBeforeHandle"
                :on-success="uploadSuccessHandle">
                <img v-if="this.blogFrom.firstPicture" :src="this.blogFrom.firstPicture" class="picture">
                <i v-else class="el-icon-plus picture-uploader-icon"></i>
              </el-upload>

              <div class="b-u-c-p-btn">
                <el-tooltip class="item" effect="light" placement="top">
                  <div slot="content">
                    为了确保博客图片能够正常显示<br>
                    请点击按钮后，左侧图片正常显示<br>
                    随机图片才算更换成功
                  </div>
                  <el-button size="mini" type="primary" @click="randomPictureHandle">随机图片</el-button>
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div class="b-u-right">
        <div class="b-u-r-title">
          博客正文
        </div>

        <div class="quill-editor"
             v-model="content"
             v-quill:quillEditor="editorOption">
        </div>

      </div>
    </div>

    <div class="b-u-p-footer">
      <el-button v-if="blogFrom.status !== '0'" type="primary" :disabled="buttonLoad" @click="commitBlogHandle(false)">修改博客</el-button>
      <el-button v-if="blogFrom.status === '0' || blogFrom.status === '2'" type="info" :disabled="buttonLoad" @click="commitBlogHandle(true)">保存博客</el-button>
      <el-button @click="closeBlogUpdatePageHandle(false)">返回</el-button>
    </div>

  </div>
</template>

<script>
  import { isImage } from "assets/js/validator";
  import { getUUID } from "assets/js/utils";

  /* 富文本插件css*/
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import Vue from 'vue'

  export default {
    layout: 'admin',
    name: "admin-blog-update",
    data() {
      return {
        // 博客表单对象
        blogFrom: {
          blogId: '',         // 博客id
          spaceId: '',        // 博客所属空间id
          title: '',          // 博客标题
          preface: '',        // 博客前言
          firstPicture: '',   // 博客首图地址
          label: 0,           // 博客标签
          tagIds: [],         // 博客关联所有系统标签id
          showStatement: 0,   // 博客是否开启版权信息
          openComment: 0,     // 博客是否开启评论
          status: '',         // 博客状态[0-草稿 1-审核 2-下架 3-发布]
        },
        // 所有上传的旧图片地址
        oldPicture: [],
        // 系统所有标签列表
        tagList: [],
        // 用户所有空间列表
        spaceList: [],
        // 阿里云oos图片上传封装对象
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossAccessKeyId: '',
          dir: '',
          host: '',
          // 过期时间
          expire: ''
        },
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 富文本内容
        content: '',
        editorOption: {
          modules: {
            toolbar: [
              ["bold", "italic", "underline", "strike"],      // 加粗 斜体 下划线 删除线
              ["blockquote", "code-block"],                   // 引用代码块
              [{ header:1 }, { header:2 }],                   // 1、2 级标题
              [{ list: "ordered" }, { list: "bullet" }],      // 有序、无序列表
              [{ script: "sub" }, { script: "super" }],       // 上标/下标
              [{ indent: "-1" }, { indent: "+1" }],           // 缩进
              [{'direction': 'rtl'}],                         // 文本方向
              [{ size: ["small", false, "large", "huge"] }],  // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6, false] }],        // 标题
              [{ color: [] }, { background: [] }],            // 字体颜色、字体背景颜色
              [{ font: [] }],                                 // 字体种类
              [{ align: [] }],                                // 对齐方式
              ["clean"],                                      // 清除文本格式
              ["link", "image", "video"]                      // 链接、图片、视频
            ]
          }
        },

        // 博客表单校验规则
        blogRules: {
          spaceId: [
            { required: true, message: '用户空间不能为空', trigger: 'blur' }
          ],
          title: [
            { required: true, message: '博客标题不能为空', trigger: 'blur' }
          ],
          preface: [
            { required: true, message: '博客前言不能为空', trigger: 'blur' }
          ],
          firstPicture: [
            { required: true, message: '博客首图不能为空', trigger: 'blur' }
          ],
        }
      }
    },
    computed: {
      // 阿里云oss上传地址
      aliUrl() {
        return process.env.Ali_URL
      },
      // 标签选择项是否可选
      tagSelect() {
        return this.blogFrom.tagIds.length > 4
      }
    },
    asyncData({ app, params, query, redirect}) {
      // return app.$axios.$get('/blog/info', { params: { blogId: params.blogId, status: params.status }} )
      //   .then(({ blog }) => {
      //     return {
      //       blogFrom: {
      //         blogId: params.blogId,
      //         spaceId: blog.spaceId,
      //         title: blog.title,
      //         preface: blog.preface,
      //         firstPicture: blog.firstPicture,
      //         label: blog.label,
      //         tagIds: blog.tagIds,
      //         showStatement: blog.showStatement,
      //         openComment: blog.openComment,
      //         status: params.status
      //       },
      //       content: blog.content
      //     }
      //   })
      //   .catch(() => {})
      if (!params.blogId || !params.status) {
        return redirect('/admin/blog/manage')
      }
      return {
        blogFrom: {
          blogId: params.blogId,
          spaceId: '',
          title: '',
          preface: '',
          firstPicture: '',
          label: 0,
          tagIds: [],
          showStatement: 0,
          openComment: 0,
          status: params.status
        }
      }
    },
    created() {
      // 引入富文本组件
      if (process.browser) {
        const VueQuillEditor = require('vue-quill-editor/dist/ssr')
        Vue.use(VueQuillEditor, /* { default global options } */)
        // 获取博客信息
        this.getBlogInfo()
        // 获取所有系统标签
        this.getAllTag()
        // 获取用户所有空间信息
        this.getAllSpace()
      }
    },
    methods: {
      // 根据博客id获取博客信息
      getBlogInfo() {
        this.$axios.$get('/blog/info', { params: { blogId: this.blogFrom.blogId }} )
          .then(({ data:blog }) => {
              this.blogFrom.spaceId = blog.spaceId
              this.blogFrom.title = blog.title
              this.blogFrom.preface = blog.preface
              this.blogFrom.firstPicture = blog.firstPicture
              this.blogFrom.label = blog.label
              this.blogFrom.tagIds = blog.tagIds
              this.blogFrom.showStatement = blog.showStatement
              this.blogFrom.openComment = blog.openComment
              this.content = blog.content
          })
          .catch(() => {})
      },
      // 获取所有系统标签
      getAllTag() {
        this.$axios.$get('/blog/tag/all/tag')
          .then(({ data }) => {
            if (!!data) {
              this.tagList = data
            }
          })
          .catch(() => {})
      },
      // 获取用户所有空间信息
      getAllSpace() {
        this.$axios.$get('/blog/space/all/space')
          .then(({ data }) => {
            if (!!data) {
              this.spaceList = data
            }
          })
          .catch(() => {})
      },
      // 产生随机图片事件
      randomPictureHandle() {
        this.blogFrom.firstPicture = `https://picsum.photos/id/${ Math.ceil(Math.random()*1084) }/350/300`
      },
      // 图片上传前调用事件
      uploadBeforeHandle(file) {
        // 校验图片
        let res = isImage(file)
        if (res.bool) {
          this.$notify({
            title: '上传失败',
            message: res.msg,
            type: 'warning',
            offset: 100,
            duration: 2000
          })
          return false
        }
        if (file.name.length > 25) {
          this.$notify({
            title: '上传失败',
            message: '图片名称不能大于25个字符!',
            type: 'warning',
            offset: 100,
            duration: 2000
          })
        }

        let _self = this
        let time = Date.now()   // 获取当前系统毫秒数
        if (_self.dataObj.policy != '' && _self.dataObj.expire != '' && time < Number(_self.dataObj.expire)) {
          _self.dataObj.key = _self.dataObj.dir + getUUID() + '_' + file.name;
          return true
        } else {
          return new Promise((resolve, reject) => {
            this.$axios.get('/oss/policy')
              .then(( { data } ) => {
                let obj = data.data
                _self.dataObj.policy = obj.policy;
                _self.dataObj.signature = obj.signature;
                _self.dataObj.ossAccessKeyId = obj.accessId;
                _self.dataObj.key = obj.dir + getUUID() + '_' + file.name;
                _self.dataObj.dir = obj.dir;
                _self.dataObj.host = obj.host;
                _self.dataObj.expire = obj.expire
                resolve(true)
              })
              .catch(err => {
                reject(false)
              })
          })
        }
      },
      // 图片上传成功后回调事件
      uploadSuccessHandle() {
        if (!this.blogFrom.firstPicture.startsWith("https://picsum") && this.blogFrom.firstPicture !== '') {
          // 保存旧图片地址
          this.oldPicture.push(this.blogFrom.firstPicture.split("com/")[1])
        }
        // 房东头像
        this.blogFrom.firstPicture = this.dataObj.host + '/' + this.dataObj.key
      },
      // 上传博客事件
      commitBlogHandle(bool) {
        this.$refs['updateBlogFrom'].validate((valid) => {
          if (!valid) {
            return
          }
          // 获取博客正文并去除正文左右两边的空白字符
          let content = this.content.trim()
          if (content.length <= 1) {
            this.notify('warning', '提示', `请输入博客正文后在进行${bool ? '保存' : '更新'}!`,)
            return
          }
          // 按钮不可被点击
          this.buttonLoad = true

          // 添加博客正文
          this.blogFrom.content = content
          let url = bool ? '/blog/save' : '/blog/update'

          this.$axios.$post(url, this.blogFrom)
            .then(() => {
              this.$notify({
                title: '修改成功',
                type: 'success',
                message: "博客修改成功",
                offset: 100,
                duration: 2000
              });

              this.closeBlogUpdatePageHandle(true)
            })
            .catch(() => {})
            .finally(() => {
              this.buttonLoad = false      // 按钮恢复可点击
            })

        })
      },
      /**
       * 关闭博客修改页面事件
       * 路由跳转回博客管理页
       * @param {Boolean} bool 路由跳转后，目标页是否刷新[true-刷新 false-不刷新]
       */
      closeBlogUpdatePageHandle(bool) {
        let status = this.blogFrom.status
        this.$refs['updateBlogFrom'].resetFields()
        // 手动清空博客id
        this.blogFrom.blogId = ''

        // 返回博客管理页面
        this.$router.push({
          name: 'admin-blog-manage',
          params: {
            'status': status,
            'refresh': bool
          }
        })
      }

    }
  }
</script>

<!--
  css字符对应
  b -> blog
  l -> left
  p -> page
  u -> update
-->
<style scoped>
  .b-u-page .b-u-content {
    position: relative;
    box-sizing: border-box;
  }
  .b-u-page .b-u-content:before, .b-u-page .b-u-content:after {
    display: table;
    content: "";
  }
  .b-u-page .b-u-content:after {
    clear: both;
  }
  .b-u-content .b-u-left {
    width: 30%;
    float: left;
    box-sizing: border-box;
  }
  .b-u-content .b-u-right {
    width: 68.7%;
    margin-left: 15px;
    float: left;
    box-sizing: border-box;
  }

  .b-u-content .b-u-c-from {
    position: relative;
    box-sizing: border-box;
  }
  .b-u-content .b-u-c-from:before, .b-u-content .b-u-c-from:after {
    display: table;
    content: "";
  }
  .b-u-content .b-u-c-from:after {
    clear: both;
  }
  .b-u-c-from .picture-upload {
    width: 65%;
    float: left;
    box-sizing: border-box;
  }
  .b-u-c-from .b-u-c-p-btn {
    width: 30%;
    line-height: 110px;
    float: left;
    box-sizing: border-box;
  }
  .b-u-c-from .b-s-c-f-statement, .b-u-c-from .b-s-c-f-comment {
    width: 50%;
    float: left;
    box-sizing: border-box;
  }

  .b-u-right .quill-editor {
    min-height: 450px;
    max-height: 450px;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow-y:auto;
  }
  /deep/ .b-u-right .ql-toolbar {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
</style>

<style scoped>
  .b-u-left .label-select, .b-u-left .tag-select, .b-u-left .space-select {
    width: 100%;
  }
  .b-u-left .b-u-l-title {
    margin-left: 20px;
    margin-bottom: 7px;
    font-weight: bold;
  }
  .b-u-right .b-u-r-title {
    margin-bottom: 7px;
    font-weight: bold;
  }

  /deep/ .b-u-left .el-radio {
   margin-right: 10px;
  }

  /deep/ .b-u-left .picture-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/ .b-u-left .picture-uploader .el-upload:hover {
    border-color: #17B3A3;
  }
  .picture-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 190px;
    height: 110px;
    line-height: 110px;
    text-align: center;
  }
  .picture {
    width: 190px;
    height: 110px;
    display: block;
  }
</style>

<style scoped>
  .b-u-page .b-u-p-footer {
    margin-top: 10px;
    text-align: center;
  }
</style>
